package cn.bytecollege.user.controller;

import cn.bytecollege.admin.service.PaymentService;
import cn.bytecollege.admin.service.ProductService;
import cn.bytecollege.common.entity.*;
import cn.bytecollege.user.service.AddressService;
import cn.bytecollege.user.service.OrderDetailService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@WebServlet(name = "OrderDetailNowbuyController",value = "/user/orderdetailsavebuy")
public class OrderDetailNowbuyController extends HttpServlet {
    OrderDetailService orderDetailService=null;
    ProductService productService=null;
    AddressService addressService=null;
    PaymentService paymentService=null;
    public OrderDetailNowbuyController(){
        orderDetailService=new OrderDetailService();
        productService=new ProductService();
        addressService=new AddressService();
        paymentService=new PaymentService();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String orderDetailId=request.getParameter("orderDetailId");
    OrderDetail orderDetail=orderDetailService.findById(Integer.valueOf(orderDetailId));
    if(orderDetail.getProductNumber()==null){
        orderDetail.setProductNumber(1);
    }
    HttpSession session= request.getSession();
    User user=(User) session.getAttribute("user");
    Integer userId=user.getUserId();
    orderDetail.setUserId(userId);
    orderDetailService.save(orderDetail);
    Product product=productService.findById(orderDetail.getProductId());
    Integer sumProduct=Integer.valueOf(orderDetail.getProductNumber());
    BigDecimal sumOrders= BigDecimal.valueOf(0);
    sumOrders=product.getProductPrice().multiply(BigDecimal.valueOf(sumProduct));
    request.setAttribute("sumOrders",sumOrders);
    request.setAttribute("sumProduct",sumProduct);
    request.setAttribute("product",product);
    List<Address> addresseslist=addressService.findlistById(userId);
    request.setAttribute("addresseslist",addresseslist);
    List<Payment> paymentList=paymentService.find();
    request.setAttribute("paymentList", paymentList);
    request.getRequestDispatcher("/order2.jsp").forward(request,response);




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }
}
